<template>
  <layout-card :filters="filterOptions" headline="遗失物品公示" @search-change="searchChange" @search-reset="searchReset">
    <template #action>
      <el-button type="primary" :class="{hideRegBtn:hideReg}" @click="handleCreate">遗失物预约登记</el-button>
    </template>
    <!-- <div class="table-common"> -->
      <div class="table-common">
        <el-radio-group class="radio-group-task" v-model="taskProcess" @change="tabChange">
          <el-radio-button label="寻找中">寻找中</el-radio-button>
          <el-radio-button label="已找回">已找回</el-radio-button>
        </el-radio-group>
      </div>
    <!-- </div> -->
    <table-common :columns="loseGoodsColumns" :loading="loading" :pagination="pager" :table-data="tableData"
      size="large" @current-change="currentChange" @size-change="sizeChange" @sort-change="sortChange">
      <template #lost_time_start="{ row }">
       <span v-if="row['lostTimeStart'] == row['lostTimeEnd']">{{ dayjs(row['lostTimeStart']).format('YYYY-MM-DD HH:mm:ss') }}</span>
       <span v-else>{{ dayjs(row['lostTimeStart']).format('YYYY-MM-DD HH:mm:ss') }} <br />至<br />{{ dayjs(row['lostTimeEnd'])?dayjs(row['lostTimeEnd']).format('YYYY-MM-DD HH:mm:ss'):'' }}</span>
      </template>
      <template #timeLimit="{ row }">
       <span>{{ row['timeLimit'] }}{{ row['timeLimitUnit'] == 'Y' ? '年' : row['timeLimitUnit'] == 'H' ? '小时' : row['timeLimitUnit'] == 'D' ? '天' : '' }}</span>
      </template>
      <template #createame="{ row }">
       <span>{{ row['creator']['name'] }}</span>
      </template>
      <template #create_time="{ row }">
       <span>{{ dayjs(row['createTime']).format('YYYY-MM-DD HH:mm:ss') }}</span>
      </template>
      <template #status="{ row }">
       <span v-if="row['status'] == 2">已找回</span>
       <span v-else-if="row['status'] == 1">寻找中</span>
       <span class="expired_overdue" v-else-if="row['status'] == 3">已过期</span>
       <span v-else>已处置</span>
      </template>
      <template #img="{ row }">
        <div v-if="row['files'] && row['files'].length > 0">
          <!-- <div v-for="(item,index) in row['files']" :key="index">
            <span class="preview-img" @click="showImage(item['resourceAddress'])">{{ item['enclosureName']}}.{{ item['enclosureSuffix'] }}</span>
            <span v-if="index != row['files'].length - 1">,</span>
          </div> -->
          <el-image class="preview-img" :src="row['files'][0]['resourceAddress']" @click="showImage(row)"></el-image>
        </div>
        <div v-else>
           <!-- <el-image :src="image.noImg"></el-image> -->
           -
        </div>
      </template>
      <template #action="{ row }">
        <!-- 自定义操作栏示例  -->
        <el-button class="link-btn" v-if="taskProcess === '已找回'" @click="handleDetail(row['lostId'])" link type="primary">详情</el-button>
        <el-button class="link-btn" v-if="taskProcess === '寻找中' && row['status'] != 3" @click="handleMatch(row)" link type="primary">匹配</el-button>
        <el-button class="link-btn" v-if="taskProcess === '寻找中' || row['status'] == 3" @click="handlerEdit(row['lostId'])" link type="primary">编辑</el-button>
        <el-button class="link-btn" v-if="taskProcess === '寻找中' || row['status'] == 3" @click="handlerRetrieved(row['lostId'])" link type="primary">已找回</el-button>
        <el-button class="link-btn light-yellow-overdue" v-if="row['status'] == 3" @click="handlerExpire(row['lostId'])" link type="primary">过期处置</el-button>
      </template>
    </table-common>
  </layout-card>
  <el-dialog v-model="imgDialogVisible" width="auto" center align-center>
    <div>
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </div>
  </el-dialog>
  <!-- 已找回弹窗 -->
  <edit-dialog :centerDialogVisible="centerDialogVisible" :tilte="tilte" @Cancel="Cancel" @Submit="Submit"
    :defaultButton="false" :width="dialogWidth">
    <template #content>
      <el-form ref="retrievedFormRef" :model="retrievedForm" :rules="rules" label-position="right" label-width="100px">
          <el-form-item label="找回时间" prop="receiveTime">
            <!-- <el-input v-model.trim="receiveForm.receiveTime"/> -->
            <el-date-picker v-model="retrievedForm.receiveTime" type="datetime" format="YYYY-MM-DD HH:mm:ss"/>
          </el-form-item>
          <el-form-item label="领取人姓名" prop="receiveName">
            <el-input v-model="retrievedForm.receiveName" placeholder="请输入领取人姓名" />
          </el-form-item>
          <el-form-item label="领取人电话" prop="receivePhone">
            <el-input min="0" v-model.trim="retrievedForm.receivePhone" placeholder="请输入领取人电话"/>
          </el-form-item>
        </el-form>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="centerDialogVisible = false">取消</el-button>
        <el-button class="buttonOk" :loading="loading" @click="handlerRetrievedSubmit(retrievedFormRef)">确定</el-button>
      </span>
    </template>
  </edit-dialog>
  <!-- 新增弹窗 -->
  <Add :visible="addDialogVisible" :isAdd="isAdd" :state="addState" :goodsType="goodsTypeDatas" :info="goodsObject" @showAdd="handleShowAdd" @cancel="Cancel" @submit="Submit"/>
  <!-- 过期处置 -->
  <Expire :visible="expireDialogVisible" :info="goodsObject" @cancel="Cancel" @submit="Submit"/>
  <!-- 匹配 -->
  <Match :visible="matchDialogVisible" :showMatch="showMatch" :state="1" :info="goodsObject" @cancel="Cancel" @submit="Submit"/>
  <!-- 已归还详情 -->
  <Detail :visible="detailDialogVisible" :info="detailData" @cancel="Cancel" @submit="Submit"/>

  <!-- 图片预览弹窗 -->
  <el-dialog align-center v-model="showImg" style="height: 700px;" center width="70%">
    <div v-if="imgList.length > 0">
      <el-carousel height="600px" indicator-position="outside" :autoplay="false">
        <el-carousel-item style="height: 600px;"
          v-for="(item, index) in imgList"
          :key="index"
        >
          <el-image style="width: 100%;height: 100%;"
            :src="item"
          >
          </el-image>
        </el-carousel-item>
      </el-carousel>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onBeforeMount, computed, watch } from 'vue'
import LayoutCard from '@/components/LayoutCard/index.vue'
import TableCommon from '@/components/TableCommon/index.vue'
import { ElMessage, FormInstance, FormRules, dayjs, type TabsPaneContext, TableColumnCtx } from 'element-plus'
import editDialog from '@/components/editDialog/index.vue'
import TablePagination from '@/components/TablePagination/index.vue'
import { filterOptions } from './config/filter'
import { lostGoodsDetail, lostGoodsPage, retrievedLostGoods } from '@/api/lose/goodsLost'
import Add from './add.vue'
import Expire from './expire.vue'
import Match from './match.vue'
import Detail from './detail.vue'
import { useStore } from 'vuex'
// 新增弹窗是否打开
const addDialogVisible = ref(false)
const expireDialogVisible = ref(false)
const centerDialogVisible = ref(false)
const matchDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const imgDialogVisible = ref(false)
const isClear = ref(false)
// 弹窗标题
const tilte = ref('找回遗失物品')
const isAdd = ref(true)
const tableData = ref([])
const dialogWidth = ref('360px')
const goodsObject = ref({})
const taskProcess = ref('寻找中')
const loading = ref(false)
const lostId = ref()
const detailData = ref({})
const addState = ref(true)
const store = useStore()
const dialogImageUrl = ref()
const imgList = ref([])
const showImg = ref(false)
const userInfo = computed(() => store.state.user.userInfo)
const hideReg = ref(false)
const detailId = ref()
const order = ref([
  {
    column: 'create_time',
    method: 'desc'
  }
])
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const retrievedFormRef = ref<FormInstance>()
interface RuleForm {
  receiveName: string;
  receivePhone: string;
  receiveTime: string;
}
const retrievedForm = reactive<RuleForm>({
  receiveName: '',
  receivePhone: '',
  receiveTime: ''
})

interface LostGooddsListItem {
  goodsType: string
  goodsName: string
  lostTimeStart: string
  lostTerminal: string
  lostPlace: string
  timeLimit: string
  goodsLimitTime: string
  lostName: string
  lostPhone: string
  createTime: string
  img: string
  state: number
}
const loseGoodsColumns = [
  {
    type: 'index',
    index: function (index: any) {
      return (pager.currentPage - 1) * pager.pageSize + index + 1
    },
    label: '序号',
    width: 60,
    align: 'center'
  },
  {
    prop: 'goodsType',
    label: '物品类型',
    minWidth: 130,
    align: 'center',
    formatter: function (row: LostGooddsListItem, column: TableColumnCtx<LostGooddsListItem>, cellValue: string) {
      return store.getters['goodsType/getGoodsTypeName'](cellValue)
    }
  },
  { prop: 'goodsName', label: '物品名称', minWidth: 200, align: 'center' },
  {
    prop: 'lost_time_start',
    label: '遗失时间',
    sortable: 'custom',
    minWidth: 250,
    align: 'center'
    // formatter: function (row:LostGooddsListItem, column:TableColumnCtx<LostGooddsListItem>, cellValue:string) {
    //   return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
    // }
  },
  { prop: 'lostTerminal', label: '航站楼', minWidth: 120, align: 'center' },
  { prop: 'lostPlace', label: '遗失地', minWidth: 120, align: 'center' },
  { prop: 'timeLimit', label: '保质期', minWidth: 120, align: 'center' },
  {
    prop: 'goods_limit_time',
    label: '保存时限',
    sortable: 'custom',
    minWidth: 180,
    align: 'center',
    formatter: function (row: LostGooddsListItem, column: TableColumnCtx<LostGooddsListItem>, cellValue: string) {
      return row.goodsLimitTime ? dayjs(row.goodsLimitTime).format('YYYY-MM-DD HH:mm:ss') : '-'
    }
  },
  {
    prop: 'lost_name',
    label: '失主姓名',
    minWidth: 120,
    sortable: 'custom',
    align: 'center',
    formatter: function (row: LostGooddsListItem, column: TableColumnCtx<LostGooddsListItem>, cellValue: string) {
      return row.lostName ? row.lostName : '-'
    }
  },
  { prop: 'lostPhone', label: '失主电话', minWidth: 130, align: 'center' },
  {
    prop: 'create_time',
    label: '登记时间',
    sortable: 'custom',
    minWidth: 180,
    align: 'center',
    // formatter: function (row: LostGooddsListItem, column: TableColumnCtx<LostGooddsListItem>, cellValue: string) {
    //   return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
    // }
  },
  {
    prop: 'createName',
    label: '登记人',
    minWidth: 120,
    align: 'center',
    formatter: function (row: LostGooddsListItem, column: TableColumnCtx<LostGooddsListItem>, cellValue: string) {
      return row.creator?.name ? row.creator?.name : '-'
    }
  },
  {
    prop: 'img',
    label: '图片',
    minWidth: 120,
    align: 'center'
  },
  {
    prop: 'status',
    label: '状态',
    fixed: 'right',
    minWidth: 80,
    align: 'center'
  },
  { prop: 'action', label: '操作', fixed: 'right', minWidth: 200, align: 'center' }
]

const validatePhone = (rule: any, value: any, callback: any) => {
  if (!value) return callback()
  if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(value)) return callback(new Error('手机号格式错误'))
  callback()
}
const rules = reactive<FormRules>({
  receiveTime: [
    { required: true, message: '请选择找回时间', trigger: 'blur' }
  ],
  receivePhone: [
    { required: false, validator: validatePhone, trigger: 'blur' }
  ]
})


const showImage = (row) => {
  console.log(row)
  if (row.files.length > 0) {
    showImg.value = true
    imgList.value = []
    for (let i = 0; i < row.files.length; i++) {
      const ele = row.files[i];
      imgList.value.push(ele.resourceAddress)
    }
  }
}

const tabChange = (value) => {
  if (value === '已找回') {
    hideReg.value = true
  } else {
    hideReg.value = false
  }
}

/**
 * 点击新增方法
 */
const handleCreate = () => {
  addDialogVisible.value = true
  isClear.value = true
  isAdd.value = true
  addState.value = false
  goodsObject.value = {}
}

/**
 * 匹配页面返回编辑需要弹出
 */
const handleShowAdd = async (val) => {
  await lostGoodsDetail(val).then(res => {
    if (res?.data) {
      addState.value = true
      isAdd.value = false
      goodsObject.value = res.data
      addDialogVisible.value = true
    } else {
      ElMessage.error(res.message || '查询详情失败')
    }
  })
}

/**
 * 点击编辑方法
 */
const handlerEdit = async (id: string) => {
  await lostGoodsDetail(id).then(res => {
    if (res?.data) {
      detailId.value = id
      addState.value = true
      isAdd.value = false
      goodsObject.value = res.data
      addDialogVisible.value = true
    } else {
      ElMessage.error(res.message || '查询详情失败')
    }
  })
}

/**
 * 点击已找回方法
 */
const handlerRetrieved = (id: string) => {
  centerDialogVisible.value = true
  lostId.value = id
  retrievedFormRef.value?.resetFields()
}

/**
 * 点击过期处置
 */
const handlerExpire = async (id: string) => {
  await lostGoodsDetail(id).then(res => {
    if (res?.data) {
      goodsObject.value = res.data
      expireDialogVisible.value = true
    } else {
      ElMessage.error(res.message || '查询详情失败')
    }
  })
}

/**
 * 物品详情
 */
const handleDetail = (id: number) => {
  lostGoodsDetail(id).then(res => {
    if (res?.data) {
      const goodsObject = {
        goodsFiles: res.data.files,
        goodsName: res.data.goodsName,
        goodsType: res.data.goodsType,
        timeLimit: res.data.timeLimit,
        timeLimitUnit: res.data.timeLimitUnit,
        lostName: res.data.lostName,
        lostPhone: res.data.lostPhone,
        lostTerminal: res.data.lostTerminal,
        lostPlace: res.data.lostPlace,
        lostTimeStart: res.data.lostTimeStart,
        lostTimeEnd: res.data.lostTimeEnd,
        goodsLimitTime: res.data.goodsLimitTime,
        createTime: res.data.createTime,
        creator: {
          id: res.data.creator.userId,
          name: res.data.creator.name,
          organName: res.data.creator.organName,
          organId: res.data.creator.organId
        }
      }
      const receiveData = {
        receiveName: res.data.findInfo.receiveName,
        receivePhone: res.data.findInfo.receivePhone,
        receiveTime: res.data.findInfo.receiveTime
      }
      detailData.value.goodsObject = goodsObject
      detailData.value.receiveData = receiveData
      detailDialogVisible.value = true
    } else {
      ElMessage.error(res.message || '获取详情失败')
    }
  }).catch(err => {
    ElMessage.error(err.message || '获取详情失败')
  })
}

const showMatch = () => {
  matchDialogVisible.value = true
}

/**
 * 点击匹配
 */
const handleMatch = (row: any) => {
  matchDialogVisible.value = true
  goodsObject.value = row
}

/**
 * 已找回提交
 */
const handlerRetrievedSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return
  }
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      retrievedForm.receiveTime = retrievedForm.receiveTime ? dayjs(retrievedForm.receiveTime).format('YYYY-MM-DD HH:mm:ss') : ''
      const payload = {
        findInfo: { ...retrievedForm },
        lastMender: {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          organId: userInfo.value.organId,
          organName: userInfo.value.organName
        },
        lostId: lostId.value
      }
      const res: any = await retrievedLostGoods(payload)
      if (res?.code === '1') {
        ElMessage.success('找回成功！')
        centerDialogVisible.value = false
        getData()
      } else {
        ElMessage.error(res?.message || '找回失败，请重试！')
      }
      console.log('Submit!')
      loading.value = false
    } else {
      console.log('error submit!', fields)
    }
  })
}

/**
 * 弹窗点击取消
 */
const Cancel = () => {
  centerDialogVisible.value = false
  addDialogVisible.value = false
  expireDialogVisible.value = false
  matchDialogVisible.value = false
  detailDialogVisible.value = false
  // getData()
}

/**
 * 弹窗点击确认
 */
const Submit = () => {
  centerDialogVisible.value = false
  addDialogVisible.value = false
  expireDialogVisible.value = false
  matchDialogVisible.value = false
  getData()
}

// 分页
const sizeChange = (size: number) => {
  pager.pageSize = size
  getData()
}
const currentChange = (value: number) => {
  pager.currentPage = value
  getData()
}

/**
 * 排序事件
 */
const sortChange = (data: any) => {
  let find = false
  order.value.forEach(ele => {
    if (ele.column === data.prop) {
      find = true
      ele.method = data.order === 'ascending' ? 'asc' : 'desc'
    }
  })
  if (!find) {
    order.value.push({ column: data.prop, method: data.order === 'ascending' ? 'asc' : 'desc' })
  }
  getData()
}

const search = ref({})
const getData = () => {
  loading.value = true
  search.value.sign = '1'
  if (taskProcess.value === '已找回') {
    search.value.sign = '2'
  }
  if (Array.isArray(search.value.lostTerminal)) {
    search.value.lostTerminal.length === 0 ? delete search.value.lostTerminal : search.value.lostTerminal = search.value.lostTerminal.join(',')
  }
  if (Array.isArray(search.value.goodsType)) {
    search.value.goodsType.length === 0 ? delete search.value.goodsType : search.value.goodsType = search.value.goodsType.join(',')
  }
  if (Array.isArray(search.value.lostTime)) {
    const data = search.value.lostTime
    delete search.value.lostTime
    if (data.length > 0) {
      search.value.startTime = data[0] + ' 00:00:00'
      search.value.endTime = data[1] + ' 23:59:59'
    }
  }
  search.value.order = order.value
  const params = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: search.value
  }
  lostGoodsPage(params).then(res => {
    if (res.data) {
      loading.value = false
      // @ts-ignore
      tableData.value = res.data.list
      tableData.value.forEach(ele => {
        ele.goodsLimitTime = setGoodsLimitTime(ele)
      })
      pager.total = res.data.total
    }
  }).catch(err => {
    loading.value = false
    ElMessage.error(err.message || '获取数据失败')
  })
}
const setGoodsLimitTime = (item:any) => {
  const { timeLimitUnit, timeLimit, lostTimeStart, lostTimeEnd } = item
  if (!lostTimeEnd && !lostTimeStart) {
    return
  }
  const unit = timeLimitUnit == 'Y' ? 'year' : timeLimitUnit == 'M' ? 'month' : 'day'
  // 计算中间值
  const middle = (dayjs(lostTimeEnd).diff(lostTimeStart, 'day')) / 2
  const goodsLimitTime =  dayjs(lostTimeStart).add(middle, 'day').add(timeLimit, unit).format('YYYY-MM-DD HH:mm:ss')
  return goodsLimitTime
}
/**
 * 点击查询
 */
const searchChange = (data: FilterDataType) => {
  search.value = data
  getData()
}

/**
 * 点击重置
 * @param data 数据
 */
const searchReset = (data: FilterDataType) => {
  search.value = data
  pager.currentPage = 1
  pager.pageSize = 10
  getData()
}

const loadTerminal = async () => {
  store.dispatch('terminal/getDict')
}

const goodsTypeDatas = computed(() => store.state.goodsType.typeList)
const loadGoodsType = () => {
  store.dispatch('goodsType/getGoodsType')
}

const loadDepositPlace = () => {
  store.dispatch('depositPlace/getDict')
}
watch(
  () => store.state.goodsType.typeList,
  () => {
    // const options: Array<any> = [{ label: '全部', value: '' }]
    const options: Array<any> = []
    let all = []
    store.state.goodsType.typeList.forEach((ele: any) => {
      options.push({ label: ele.goodsType, value: ele.typeId })
      all.push(ele.typeId)
    })
    options[0].value = all.join(',')
    filterOptions.value[0].inputProps.options = options
  }
)

watch(
  () => store.state.terminal.data, () => {
    const options: Array<any> = []
    store.state.terminal.data.forEach((ele: any) => {
      options.push(ele)
    })
    filterOptions.value[4].inputProps.options = options
  }
)
watch(
  () => taskProcess.value,
  () => {
    tableData.value = []
    pager.currentPage = 1
    pager.pageSize = 10
    getData()
  }
)
const initData = () => {
  // 获取航站楼
  loadTerminal()
  // 获取物品类型
  loadGoodsType()
  loadDepositPlace()
  getData()
}
onBeforeMount(initData)
</script>

<style lang="less" scoped>
  @import url('./index.less');
</style>
